package com.wealth.scsj.b_app.view.activity.shopregistermodel;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
//import com.scsj.supermarket.utils.ImageLoder;
//import com.scsj.supermarket.view.activity.mapmodel.AddShopMarkActivity;
import com.vondear.rxtools.RxPhotoTool;
import com.vondear.rxtools.RxSPTool;
import com.vondear.rxtools.view.dialog.RxDialogChooseImage;
import com.wealth.scsj.b_app.R;
import com.wealth.scsj.b_app.bean.ShoperCommitInfoBean;
import com.wealth.scsj.b_app.utils.GetFileByUri;
import com.wealth.scsj.b_app.utils.SkipUtils;
import com.wealth.scsj.b_app.view.activity.BaseActivity;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;
//import com.yalantis.ucrop.UCrop;
//import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import es.dmoral.toasty.Toasty;

import static com.vondear.rxtools.view.dialog.RxDialogChooseImage.LayoutType.TITLE;

/**
 * 商家申请入驻第二步
 */

public class RegisterFirstStepActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout nextBtnRl;
    private LinearLayout upLoadShopLogo, uploadShopInfoImg;
    private ImageView shop_logo_iv, shop_info_iv;
    private Uri resultUri;
    private int whichImg;
    private RadioGroup chooseShopTypeRg;
    private RadioButton radioButton;
    private EditText shopNameEt, shopAddressEt, shopDetailAddressEt;
    private TextView shopAddressMarkTv;
    private LinearLayout locationMarkLl;

    public static final int GOMAPCODE = 1001;
    private ShoperCommitInfoBean shoperCommitInfoBean;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_resiste_first_step);
    }

    @Override
    protected void initView() {
        shoperCommitInfoBean = new ShoperCommitInfoBean();
        nextBtnRl = findViewById(R.id.registerfirst_next_rl);
        upLoadShopLogo = findViewById(R.id.upload_shop_logo);
        uploadShopInfoImg = findViewById(R.id.upload_shop_info_img);
        shop_logo_iv = findViewById(R.id.shop_logo_iv);
        shop_info_iv = findViewById(R.id.shop_info_iv);
        chooseShopTypeRg = findViewById(R.id.choose_shop_type_rg);
        shopNameEt = findViewById(R.id.shop_name);
        shopAddressEt = findViewById(R.id.shop_address);
        shopDetailAddressEt = findViewById(R.id.shop_detail_address);
        shopAddressMarkTv = findViewById(R.id.shop_address_mark);
        locationMarkLl = findViewById(R.id.location_mark_ll);


        //TODO 暂去登录页面

        findViewById(R.id.test111).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SkipUtils.toLogin(RegisterFirstStepActivity.this);
            }
        });
    }
    @Override
    protected void initListener() {
        nextBtnRl.setOnClickListener(this);
        upLoadShopLogo.setOnClickListener(this);
        uploadShopInfoImg.setOnClickListener(this);
        locationMarkLl.setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.registerfirst_next_rl:
                //跳转到下一个页面
                SkipUtils.toRegisterSecondStep(this, shoperCommitInfoBean);
                //店铺类型
                radioButton = findViewById(chooseShopTypeRg.getCheckedRadioButtonId());
                String shopTypeStr = radioButton.getText().toString();
                //店铺名称
                String shopNameStr = shopNameEt.getText().toString();
                //店铺地址
                String shopAddressStr = shopAddressEt.getText().toString();
                //店铺详细地址
                String shopDetailAddress = shopDetailAddressEt.getText().toString();
                //位置标记
                String shopAddressMark = shopAddressMarkTv.getText().toString();

                if (TextUtils.isEmpty(shopTypeStr)) {
                    Toasty.info(RegisterFirstStepActivity.this, "请选择店铺类型").show();
                    return;
                } else if (TextUtils.isEmpty(shopNameStr)) {
                    Toasty.info(RegisterFirstStepActivity.this, "店铺名字不能为空").show();
                    return;
                } else if (TextUtils.isEmpty(shopAddressStr)) {
                    Toasty.info(RegisterFirstStepActivity.this, "店铺地址不能为空").show();
                    return;
                } else if (TextUtils.isEmpty(shopDetailAddress)) {
                    Toasty.info(RegisterFirstStepActivity.this, "店铺详细地址不能为空").show();
                    return;
//                } else if (TextUtils.isEmpty(shopAddressMark)||"+添加标记".equals(shopAddressMark)) {
//                    Toasty.info(RegisterFirstStepActivity.this, "位置标记不能为空").show();
//                    return;
                } else {
                    /**
                     * 设置各个属性的值
                     */

                    //店铺类型:22天街网店23实体店24直营店铺
                    if ("天街网店".equals(shopTypeStr)) {
                        shoperCommitInfoBean.setShopType("22");
                    } else if ("实体店".equals(shopTypeStr)) {
                        shoperCommitInfoBean.setShopType("23");
                    } else if ("直营店铺".equals(shopTypeStr)) {
                        shoperCommitInfoBean.setShopType("24");
                    }
                    shoperCommitInfoBean.setShopName(shopNameStr);
                    shoperCommitInfoBean.setShopAddress(shopAddressStr);
                    shoperCommitInfoBean.setShopDetailAddress(shopDetailAddress);
                    shoperCommitInfoBean.setShopMark(shopAddressMark);

                    //跳转到下一个页面
                    SkipUtils.toRegisterSecondStep(this, shoperCommitInfoBean);
                }
                break;
            case R.id.upload_shop_logo:
                //上传店铺logo
                whichImg = 0;
                initDialogChooseImage();
                break;
            case R.id.upload_shop_info_img:
                //上传门头信息
                whichImg = 1;
                initDialogChooseImage();
                break;
            case R.id.location_mark_ll:
                //进入百度地图
                //SkipUtils.toAddShopMarkPage(this);
//                Intent intent = new Intent(mContext, AddShopMarkActivity.class);
//                startActivityForResult(intent, GOMAPCODE);
                break;
        }
    }

    private void initDialogChooseImage() {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this, TITLE);
        dialogChooseImage.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //用来区分是哪个ImageView上传的图片
        ImageView imageView = null;
        if (whichImg == 0) {
            imageView = shop_logo_iv;
        } else if (whichImg == 1) {
            imageView = shop_info_iv;
        }
        //上传图片的同时将图片控件显示出来
        imageView.setVisibility(View.VISIBLE);
        switch (requestCode) {
            case GOMAPCODE://进入地图之后处理数据
                imageView.setVisibility(View.GONE);
                if (data.getStringExtra("address_name") != null) {
                    String markName = data.getStringExtra("address_name");
                    shopAddressMarkTv.setText(markName);
                }
                if (data.getStringExtra("detail_address") != null) {
                    String detailAddress = data.getStringExtra("detail_address");
                    shopDetailAddressEt.setText(detailAddress);
                }
                double lat = data.getDoubleExtra("lat",0);
                double lon = data.getDoubleExtra("lon",0);
                String country = data.getStringExtra("country");
                String street = data.getStringExtra("street");
                String streetNumber = data.getStringExtra("streetNumber");
                String province = data.getStringExtra("province");
                String business = data.getStringExtra("business");
                String city = data.getStringExtra("city");
                String district = data.getStringExtra("district");

                Log.e("位置信息：：",lat+"纬度");

                if (lat != 0) {
                    shoperCommitInfoBean.setLat(lat);
                }else if (lon!=0){
                    shoperCommitInfoBean.setLon(lon);
                }else if (country!=null){
                    shoperCommitInfoBean.setCountry(country);
                }else if (street!=null){
                    shoperCommitInfoBean.setStreet(street);
                }else if (streetNumber!=null){
                    shoperCommitInfoBean.setStreetNumber(streetNumber);
                }else if (province!=null){
                    shoperCommitInfoBean.setProvince(province);
                }else if (business!=null){
                    shoperCommitInfoBean.setBusiness(business);
                }else if (city!=null){
                    shoperCommitInfoBean.setCity(city);
                }else if (district!=null){
                    shoperCommitInfoBean.setDistrict(district);
                }
                break;

            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }
                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);
                }
                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                Glide.with(this).
                        load(RxPhotoTool.cropImageUri).
                        diskCacheStrategy(DiskCacheStrategy.RESULT).
                        thumbnail(0.5f).
                        placeholder(R.drawable.ic_launcher_background).
                        priority(Priority.HIGH).
                        error(R.drawable.ic_launcher_background).
                        fallback(R.drawable.ic_launcher_background).
                        into(imageView);

                //开始上传图片
                //获取图片真实路径
//                String path = GetFileByUri.getFileByUri(resultUri, getApplicationContext()).getPath();
//                ImageLoder imageLoder = new ImageLoder();
//                imageLoder.startLoad(path, shoperCommitInfoBean,whichImg);
                break;
            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    roadImageView(resultUri, imageView);
                    RxSPTool.putContent(this, "AVATAR", resultUri.toString());
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initUCrop(Uri uri) {
        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));
        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.colorPrimary));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.colorPrimaryDark));
        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
        //options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);
        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withOptions(options)
                .start(this);
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {
        Glide.with(this).
                load(uri).
                diskCacheStrategy(DiskCacheStrategy.RESULT).
                placeholder(R.drawable.ic_launcher_background).
                priority(Priority.LOW).
                error(R.drawable.ic_launcher_background).
                fallback(R.drawable.ic_launcher_background).
                into(imageView);

//        //开始上传图片
//        ImageLoder imageLoder = new ImageLoder();
//        //获取图片真实路径
//        String path = GetFileByUri.getFileByUri(resultUri, getApplicationContext()).getPath();
//        imageLoder.startLoad(path, shoperCommitInfoBean, whichImg);

        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }
}
